﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using AutoMail.Data;
using AutoMail.Models;
using Newtonsoft.Json;
using AutoMail.Service.Interface;
using AutoMail.QuartzJobs.Interfaces;

namespace AutoMail.Controllers
{
    public class MailSendingSettingsController : Controller
    {
        private readonly IConfiguration _configuration;
        private readonly IQuartzService _quartzService;
        private readonly IJobsManager _jobsManager;

        public MailSendingSettingsController(IConfiguration configuration, IQuartzService quartzService, IJobsManager jobsManager)
        {
            _configuration = configuration;
            _quartzService = quartzService;
            _jobsManager = jobsManager;
        }

        // GET: MailSendingSettings/Edit/5
        public async Task<IActionResult> MailSendingSetting()
        {
            string settingFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _configuration["EmailSendingSetting"]);
            if (System.IO.File.Exists(settingFilePath))
            {
                var settingsModel = JsonConvert.DeserializeObject<SettingDetailsViewModel>(System.IO.File.ReadAllText(settingFilePath));
                return View(settingsModel);
            }

            return View();
        }

        // POST: MailSendingSettings/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> MailSendingSetting([Bind("Id,BirthdayMailSendTimeHour" +
            ",BirthdayMailSendTimeMinute,BirthdayMailSendTimeSecond,AnniversaryMailSendTimeHour" +
            ",AnniversaryMailSendTimeMinute,AnniversaryMailSendTimeSecond,SmtpHost,SmtpPort,UserName" +
            ",Password,From,Encoding,EnableSsl")] SettingDetailsViewModel settingDetailsViewModel)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string settingFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _configuration["EmailSendingSetting"]);
                    System.IO.File.WriteAllText(settingFilePath, JsonConvert.SerializeObject(settingDetailsViewModel));
                }
                catch (Exception)
                {
                    return NotFound();
                }

                _jobsManager.RefreshMailSendConfig(); // 刷新为最新配置

                // Update all Jobs with new settings
                var quartzScheduler = _quartzService.GetCurrentScheduler();
                await _jobsManager.UpdateAllJobs(quartzScheduler);

                return RedirectToAction("Index", "EmailJobs");
            }

            return View(settingDetailsViewModel);
        }
    }
}
